package utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.SQLException;
import java.util.Calendar;

public class StackTracePrinter {



	public static void print(Exception exception)	{ 
		try {

			File file = new File ("stackTrace.txt");
			if (!file.exists())
				file.createNewFile();

			StringWriter sw = new StringWriter(); 
			PrintWriter pw = new PrintWriter(sw); 

			if (exception instanceof SQLException) {
				if (ignoreSQLException(((SQLException)exception).getSQLState()) == false) {
					
					String newLine = System.getProperty("line.separator");
					
					String state = "SQLState: " + ((SQLException)exception).getSQLState();
					String code = "Error Code: " + ((SQLException)exception).getErrorCode();
					String message = "Message: " + exception.getMessage();
					
					System.err.println(state);
					System.err.println(code);
					System.err.println(message);
					
					pw.write(state+newLine);
					pw.write(code+newLine);
					pw.write(message+newLine);
					
					Throwable t = exception.getCause();
					while (t != null) {
						String cause = "Cause: " + t;
						System.err.println(cause);
						pw.write(cause+newLine);
						t = t.getCause();
					}
				}
			}
			exception.printStackTrace();
			exception.printStackTrace(pw); 

			BufferedWriter writer = new BufferedWriter(new FileWriter(file,true));
			writer.write("PRINTING DATE: "+Calendar.getInstance().getTime().toString());
			writer.newLine();
			writer.write(sw.toString());
			writer.newLine();
			writer.newLine();
			writer.close() ;

		} catch (IOException e) {
			System.err.println("EXCEPTION IN STACK PRINTER.");
			e.printStackTrace();
		} 

	}

	private static boolean ignoreSQLException(String sqlState) {
		if (sqlState == null) {
			System.out.println("The SQL state is not defined!");
			return false;
		}
		// X0Y32: Jar file already exists in schema
		if (sqlState.equalsIgnoreCase("X0Y32"))
			return true;
		// 42Y55: Table already exists in schema
		if (sqlState.equalsIgnoreCase("42Y55"))
			return true;
		return false;
	}
}
